package com.itheima.day16.reflect.test4;

import java.lang.reflect.Field;

//        Class类获取成员变量对象的方法
public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        // method1();
        // method2();
        // method3();
        // method4();


    }

    private static void method4() throws ClassNotFoundException, NoSuchFieldException {
        //        Field getDeclaredField(String name)	返回单个成员变量对象
        // 1.获取class对象
        Class className = Class.forName("com.itheima.day16.reflect.test4.Student");

        // 2.获取money这个私有成员变量
        Field field = className.getDeclaredField("money");

        // 3.打印
        System.out.println(field);
    }

    private static void method3() throws ClassNotFoundException, NoSuchFieldException {
        //        Field getField(String name)        	返回单个公共成员变量对象
        // 1.获取class对象
        Class className = Class.forName("com.itheima.day16.reflect.test4.Student");

        // 2.获取name这个成员变量
        Field field = className.getField("name");
        // Field field = className.getField("name1"); // NoSuchFieldException: name1
        // Field field = className.getField("money"); // NoSuchFieldException: money

        // 3.打印
        System.out.println(field);
    }

    private static void method2() throws ClassNotFoundException {
        //        Field[] getDeclaredFields()        	返回所有成员变量对象的数组
        // 1.获取class对象
        Class className = Class.forName("com.itheima.day16.reflect.test4.Student");

        // 2.获取所有Fiele对象
        Field[] declaredFields = className.getDeclaredFields();

        // 3.遍历
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
    }

    private static void method1() throws ClassNotFoundException {
        //        Field[] getFields()                	返回所有公共成员变量对象的数组
        // 1.获取class对象
        Class className = Class.forName("com.itheima.day16.reflect.test4.Student");

        // 2.获取所有的公共Field对象
        Field[] fields = className.getFields();

        // 3.遍历
        for (Field field : fields) {
            System.out.println(field);
        }
    }
}
